<template>
  <div class="employees-container">
    <div class="app-container">
      <!-- 通用工具栏组件使用 -->
      <page-tools>
        <!-- 自定义左侧内容 -->
        <template #slot-left>
          <span>共 19 条记录</span>
        </template>

        <!-- 自定义右侧内容 -->
        <template #slot-right>
          <el-button v-power="'import'" type="danger" size="small" @click="$router.push('/excel')">导入excel</el-button>
          <el-button v-power="'export'" type="success" size="small" @click="exportExcelFn">导出excel</el-button>
          <el-button type="primary" size="small" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="employeesList">
          <el-table-column type="index" label="序号" />
          <el-table-column prop="username" label="姓名" />
          <el-table-column label="头像" width="120">
            <template slot-scope="scope">
              <image-holder class="staffPhoto" :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column prop="mobile" label="手机号" />
          <el-table-column prop="workNumber" label="工号" sortable :sort-method="sortWorkNumberFn" />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template v-slot="scope">
              <span>{{ formatEmployeeFn(scope.row.formOfEmployment) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" />
          <el-table-column label="操作" width="280">
            <template v-slot="scope">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail?id=${scope.row.id}` )">查看</el-button>
              <el-button type="text" size="small" @click="setEmp(scope.row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="delEmp(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <!-- 分页区域 -->
          <el-pagination
            :current-page="query.page"
            :page-sizes="[10, 15, 20, 25]"
            :page-size="query.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>

      <!-- 新增员工弹框组件 -->
      <el-dialog title="新增员工" :visible.sync="showDialog" @close="dialogCloseFn">
        <EmpForm ref="empForm" :tree-data="treeData" @close="fromCloseFn" @add-emp="addEmpFn" />
      </el-dialog>

      <!-- 员工-分配角色权限 - 弹窗 -->
      <el-dialog title="分配角色" :visible="showRoleDialog" @close="cancleDialog">
        <!-- 设置角色组件 -->
        <AssignRoleDialog ref="roleDialog" :user-id="employeeId" :role-list="roleList" @close="showRoleDialog = false" @confirm="confirmFn" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getEmployeeListAPI, getDepartmentsListAPI, addEmployeeAPI, delEmployeeAPI, getRolesAPI, getUserDetailByIdAPI, assignRolesAPI } from '@/api/index'
import EmpForm from './components/empForm.vue'
import { transTree } from '@/utils'
import AssignRoleDialog from './components/assignRoleDialog.vue'
export default {
  name: 'Employees',
  components: {
    EmpForm, // 新增员工
    AssignRoleDialog // 分配角色
  },
  data() {
    return {
      query: {
        page: 1, // 页码
        size: 10 // 每页条数
      },
      employeesList: [], // 员工列表
      total: 0, // 数据总条数
      showDialog: false, // 添加员工组件的展示
      treeData: [], // 部门数据
      showRoleDialog: false, // 角色分配 - 弹窗是否显示/隐藏
      employeeId: 0, // 角色分配 - 员工ID
      roleList: [] // 角色列表数据
    }
  },
  created() {
    // 员工列表
    this.getEmployeeListFn()
    // 部门列表 -> 查看员工详情页面
    this.getDepartmentsListFn()
    // 角色列表
    this.getRolesListFn()
  },
  methods: {
    // 请求 - 获取员工列表
    async getEmployeeListFn() {
      const res = await getEmployeeListAPI(this.query)
      console.log(res)
      this.employeesList = res.data.rows
    },
    // 请求 - 部门列表数据
    async getDepartmentsListFn() {
      const res = await getDepartmentsListAPI()
      this.treeData = transTree(res.data.depts, '')
    },
    // 请求- 获取角色列表
    async getRolesListFn() {
      const res = await getRolesAPI()
      console.log(res)
      this.roleList = res.data.rows
    },
    // 删除 - 点击事件
    async delEmp(id) {
      // 显示删除询问对话框
      const delRes = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      // 用户点击了取消，给用户进行提示
      if (delRes === 'cancel') return this.$message.info('您取消了删除')

      const res = await delEmployeeAPI(id)
      if (!res.success) return this.$message.error(res.message)
      // 删除成功后的提示
      this.$message.success(res.message)

      // 判断是不是最后一条数据
      if (this.employeesList.length === 1) {
        this.query.page--
        if (this.query.page <= 0) {
          this.query.page = 1
        }
      }
      // 重新获取数据
      this.getEmployeeList()
    },
    // 聘用形式 - 数字转中文
    formatEmployeeFn(str) {
      if (String(str) === '1' || str === '正式') {
        return '正式'
      } else {
        return '非正式'
      }
    },
    // 工号 - 格式化
    formatWorkNumberFn(row) {
      return row.workNumber * 1 // 字符串转成数字然后对比排序
    },
    // 工号 - 自定义排序过程
    sortWorkNumberFn(a, b) {
      return a.workNumber - b.workNumber
    },

    // 每页显示的条数发生改变时触发
    handleSizeChange(newSize) {
      this.query.size = newSize
      this.getEmployeeListFn()
    },

    // 当前页面发生改变时触发
    handleCurrentChange(newPage) {
      this.query.page = newPage
      this.getEmployeeListFn()
    },

    // 表单 - 确定和取消按钮 -> 弹窗关闭
    fromCloseFn() {
      this.showDialog = false
    },

    // 表单
    async addEmpFn(formData) {
      const res = await addEmployeeAPI(formData)
      console.log(res)
    },

    // 弹窗被关闭->检测到事件
    dialogCloseFn() {
      this.$refs.empForm.$refs.addForm.resetFields()
    },

    // 表格 - 导出 - 点击事件
    exportExcelFn() {
      import('@/vendor/Export2Excel').then(excel => {
        // 1. 数据映射数组(顺序)-8列和页面一样
        const arr = [
          {
            key: 'id',
            name: '序号'
          },
          {
            key: 'username',
            name: '姓名'
          },
          {
            key: 'staffPhoto',
            name: '头像'
          },
          {
            key: 'mobile',
            name: '手机号'
          },
          {
            key: 'workNumber',
            name: '工号'
          },
          {
            key: 'formOfEmployment',
            name: '聘用形式'
          },
          {
            key: 'departmentName',
            name: '部门'
          },
          {
            key: 'timeOfEntry',
            name: '入职日期'
          }
        ]
        const headerArr = arr.map(obj => obj.name)
        const rowsArr = this.employeesList
        const data = rowsArr.map((obj, index) => {
          const keyArr = arr.map(obj => obj.key)
          const values = keyArr.map(enKey => {
            if (enKey === 'id') {
              return index + 1
            } else if (enKey === 'formOfEmployment') {
              const value = obj[enKey]
              if (String(value) === '1' || value === '正式') {
                return '正式'
              } else {
                return '非正式'
              }
            } else {
              return obj[enKey]
            }
          })
          return values
        })

        excel.export_json_to_excel({
          header: headerArr,
          data,
          filename: '1.xlsx',
          autoWidth: true,
          bookType: 'xlsx'
        })
      })
    },

    // 角色分配 - 弹窗 - 关闭事件
    cancleDialog() {
      this.showRoleDialog = false
      this.$refs.roleDialog.roleIdArr = []
    },

    // 表格 - 角色分配按钮 - 点击事件
    async setEmp(id) {
      this.employeeId = id
      this.showRoleDialog = true

      const res = await getUserDetailByIdAPI(id)
      console.log(res)
      this.$refs.roleDialog.roleIdArr = res.data.roleIds || []
    },

    // 角色分配 - 弹窗 - 确定事件
    async confirmFn(roleIdArr) {
      const res = await assignRolesAPI({
        id: this.employeeId,
        roleIds: roleIdArr // 角色id数组
      })
      if (res.success) this.$message.success(res.message)
      this.cancleDialog() // 关闭弹窗
    }
  }
}
</script>

<style lang="scss" scoped>
.staffPhoto {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}
</style>
